﻿using System;
using System.Windows;
using System.IO;
using System.Windows.Markup;
using FireFly;

namespace XAMLStylePad.Models
{
    /// <summary>
    /// Xaml file as source
    /// </summary>
    public class XamlSource : SourceBase
    {
        public XamlSource()
        {
        }

        public XamlSource(string fullPath)
            : base(fullPath)
        {
            IsNew = !File.Exists(fullPath);
        }

        public bool IsNew
        {
            get;
            private set;
        }

        public string Code
        {
            get;
            set;
        }

        public override bool IsReadOnly
        {
            get
            {
                return false;
            }
        }

       

        public override void Load()
        {
            if(File.Exists(FullPath))
                Code = File.ReadAllText(FullPath);

            try
            {
                var obj = XamlReader.Parse(Code);
                if(obj is ResourceDictionary)
                {
                    this.Resources.Add(new ResourceDictionaryModel(obj as ResourceDictionary)
                    {
                        FileName = Name
                    });
                }
                else if(obj is FrameworkElement)
                {
                    var list = XamlSPViewModelService.GetDictionaries(obj as FrameworkElement);
                    if(list != null && list.Count > 0)
                        Resources.AddRange(list.ConvertAll<ResourceDictionaryModel>(res => new ResourceDictionaryModel(res)));
                }
            }
            catch(Exception err)
            {
                ViewModelService.Instance.ProcessException(err);
            }

            IsLoaded = true;
        }

        public override void Save(string path)
        {
            using(var file = File.CreateText(path))
            {
                file.Write(Code);
                file.Flush();
            }
        }
    }
}